package com.wanyangproject.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.activity.DiTuActivity;
import com.wanyangproject.entity.ShangJiaShangPinEntity;
import com.wanyangproject.my.ShangJiaGuanLiActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 甜甜 on 2018/7/20.
 */
// 外卖商家
public class ShangJiaFragment extends Fragment {

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_peisong_shijian)
    TextView tvPeisongShijian;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.image_ditu)
    ImageView imageDitu;
    private String token;
    private ShangJiaShangPinEntity shangJiaShangPinEntity;
    private WebSettings mWebSettings;
    private String content;
    private String shopid;
    private ProgressDialog progressDialog;

    public String getShopid() {
        return shopid;
    }

    public void setShopid(String shopid) {
        this.shopid = shopid;
    }


    private static Boolean isOK = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.shangjia_fragment, container, false);
        ButterKnife.bind(this, view);
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("token", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "token");
        System.out.println(token + "     token");

        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//        mWebSettings.setTextSize(WebSettings.TextSize.SMALLER);


//        商家的网络请求
        initShangJiaShangPinHttp();

        initView();

        return view;
    }

    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return WebViewUtils.shouldOverrideUrlLoading(view, request, getContext());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view, url, getContext());

            }


            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("111111111111111111");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }


            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");


                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }


            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);


                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }
        });
    }


    //    商家的网络请求
//    tiantian
    private void initShangJiaShangPinHttp() {
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Life/shop")
                .addHeader("token", ContractUtils.getTOKEN(getContext()))
                .addParams("parkId", ContractUtils.getParkId(getContext()))
                .addParams("shopId", shopid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(getContext(), response);
//                        progressDialog.dismiss();
                        ContractUtils.Code500(getContext(), response);
                        System.out.println(response + "      商家的网络请求");
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            shangJiaShangPinEntity = gson.fromJson(response, ShangJiaShangPinEntity.class);

//                        营业时间
                            if (shangJiaShangPinEntity.getResponse().getShop().getShop().getStar_time() == null && shangJiaShangPinEntity.getResponse().getShop().getShop().getEnd_time() == null) {

                            } else {
                                tvTime.setText("营业时间： " + shangJiaShangPinEntity.getResponse().getShop().getShop().getStar_time() + "-" + shangJiaShangPinEntity.getResponse().getShop().getShop().getEnd_time());
                            }

//                        商家位置
                            if (shangJiaShangPinEntity.getResponse().getShop().getShop().getBaidu_address() == null) {

                            } else {
                                tvAddress.setText(shangJiaShangPinEntity.getResponse().getShop().getShop().getBaidu_address());
                            }

//                      电话咨询
                            if (shangJiaShangPinEntity.getResponse().getShop().getShop().getPhone() == null) {

                            } else {
                                tvPhone.setText("电话咨询： " + shangJiaShangPinEntity.getResponse().getShop().getShop().getPhone());
                            }

//                        配送时间
                            if (shangJiaShangPinEntity.getResponse().getShop().getShop().getStar_time() == null && shangJiaShangPinEntity.getResponse().getShop().getShop().getEnd_time() == null) {

                            } else {
                                tvPeisongShijian.setText("配送时间： " + shangJiaShangPinEntity.getResponse().getShop().getShop().getStar_time() + "-" + shangJiaShangPinEntity.getResponse().getShop().getShop().getEnd_time());
                            }

//                        商家简介
                            if (shangJiaShangPinEntity.getResponse().getShop().getShop().getContent() == null) {

                            } else {
                                content = shangJiaShangPinEntity.getResponse().getShop().getShop().getContent();

                                String newContent = getNewContent(content);
                                if(!newContent.endsWith("</p>")){
                                    newContent = newContent + "</p>";
                                }
                                webView.loadDataWithBaseURL("http://www.baidu.com", "<style>* {font-size:14px;line-height:20px;}p {color:#000000;}</style>"+newContent, "text/html", "UTF-8", null);
//                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content), "text/html", "UTF-8", null);
                            }
                        }
                    }
                });
    }


    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {
//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }



    @OnClick({R.id.tv_address, R.id.image_ditu, R.id.tv_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_address:
                break;
            case R.id.image_ditu:
                if(shangJiaShangPinEntity == null){
                    return;
                }


                if(shangJiaShangPinEntity.getResponse().getShop().getShop().getLat().equals("") && shangJiaShangPinEntity.getResponse().getShop().getShop().getLng().equals("")){
                    Toast.makeText(getContext(), "暂无地址！", Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent1 = new Intent(getContext(), DiTuActivity.class);
                intent1.putExtra("lat",shangJiaShangPinEntity.getResponse().getShop().getShop().getLat());
                intent1.putExtra("lng",shangJiaShangPinEntity.getResponse().getShop().getShop().getLng());
                intent1.putExtra("name",shangJiaShangPinEntity.getResponse().getShop().getShop().getNickname());
                startActivity(intent1);

//                Intent intent = new Intent(getContext(), DiTuActivity.class);
//                startActivity(intent);
                break;
            case R.id.tv_phone:
                break;
        }
    }
}
